package com.bjpowernode.security04mysql.filter;

import com.bjpowernode.security04mysql.vo.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 检查验证码的过滤器
 */
@Component
public class CaptchaCodeFilter extends OncePerRequestFilter {

    @Resource
    private ObjectMapper objectMapper;


    /**
     *  检查验证码
     *  1.判断当前是否为登录请求
     *  2.获取表单传入的验证码和session中的验证码比对
     *  3.成功（放行）或失败（禁行）
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //处理字符编码
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");

        //1.判断当前是否为登录请求
        String requestURI = request.getRequestURI();
        if (requestURI.equals("/login/doLogin")){
            //若进来则是登录请求
            //2.获取表单传入的验证码和session中的验证码比对

            //获取session中的验证码
            String sessionCode = (String) request.getSession().getAttribute("code");

            //获取用户输入的验证码
            String code = request.getParameter("code");
            //忽略大小写比较
            if (!sessionCode.equalsIgnoreCase(code)) {
                //若程序进来则验证码不一致，给前端返回json数据
                Result result = new Result(-1, "验证码不一致");

                String jsonStr = objectMapper.writeValueAsString(result);

                //响应给前端
                response.getWriter().write(jsonStr);

                //拦截
                return;

            }
        }


        //放行
        filterChain.doFilter(request, response);
    }
}
